package com.yx.modules.api.controller;


import com.yx.common.annotation.Log;
import com.yx.common.annotation.LoginUser2;
import com.yx.common.utils.PageUtils;
import com.yx.common.utils.Query;
import com.yx.common.utils.R;
import com.yx.modules.api.annotation.AuthIgnore;
import com.yx.modules.api.annotation.LoginUser;
import com.yx.modules.api.entity.TbBookRecommendRecord;
import com.yx.modules.api.entity.TbClick;
import com.yx.modules.api.entity.TbGradeRecord;
import com.yx.modules.api.entity.TbUser;
import com.yx.modules.api.service.TbBookRecommendRecordService;
import com.yx.modules.api.service.TbClickService;
import com.yx.modules.api.service.TbGradeRecordService;
import com.yx.system.entity.*;
import com.yx.system.service.TdBookService;
import com.yx.system.service.TdCollectionService;
import com.yx.system.service.TdOrderService;
import com.yx.system.service.TdSectionService;
import com.yx.utils.DateUtil;
import com.yx.utils.PayStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 书籍控制器
 */
@RestController
@RequestMapping("/api/book")
public class TdBookController {

    @Autowired
    private TdBookService tdBookService;

    @Autowired
    private TdOrderService tdOrderService;

    @Autowired
    private TdCollectionService tdCollectionService;

    @Autowired
    private TbClickService clickService;

    @Autowired
    private TbGradeRecordService tbGradeRecordService;

    @Autowired
    private TdSectionService tdSectionService;

    @Autowired
    private TbBookRecommendRecordService tbBookRecommendRecordService;

    /**
     * 按ID查询书籍
     *
     * @return
     */
    @AuthIgnore
    @PostMapping("info")
    public R findById(int id) {
        TdBook tdBook = tdBookService.selectByPrimaryKey(id);
        tdBook.setChecknum(tdBook.getChecknum() + 1);
        //计算图书字数
        List<TdSection> sections = tdSectionService.findByBookid(tdBook.getId());
        if (sections.size()!=0){
            int sum = 0;
            for (TdSection tdSection:sections){
                sum += tdSection.getFontsize();
            }
            tdBook.setFontCount(sum);
        }
        //在点击对象中存入数据
        TbClick tbClick = new TbClick();
        Date date = new Date();
        tbClick.setBookId(tdBook.getId());
        tbClick.setClickDate(date);
        tbClick.setClickYear(DateUtil.getYear(date));
        tbClick.setClickMonth(DateUtil.getMonth(date));
        tbClick.setClickWeek(DateUtil.getDay(date));
        tbClick.setClickCount(1);
        //保存数据
        clickService.save(tbClick);
        tdBookService.updateByPrimaryKey(tdBook);
        return R.ok().put("book", tdBook);
    }

    /**
     * 按条件查询所有
     * <p>
     * 查询所有（按条件查询）
     * 是否三界都在看 isSanjie;
     * 是否中原武侠 isWuxia;
     * 是否仙界大陆 isXianjie;
     * 是否奇幻世界 isQihuan;
     * 是否宫廷男爵 isGongting;
     * 是否现言优选 i sXianyan;
     * 是否主编精选 isJingxuan;
     * 分类ID categoryid;
     * 连载or完结 bookType;
     * 字数分类    wordType;
     * 是否付费    ispay;
     *
     * @return
     */
    @AuthIgnore
    @PostMapping("findAllByCondition")
    public R findAllByCondition(@RequestParam Map<String, Object> map) {
        if (map.get("type")!=null){
        if (map.get("type").equals("1")){
            map.put("checknum","1");
        }
        if (map.get("type").equals("2")){
            map.put("updatedate","1");
        }
        if (map.get("type").equals("3")){
            map.put("createdate","1");
        }
        if (map.get("type").equals("4")){
            map.put("commentCount","1");
        }
        if (map.get("type").equals("5")){
                map.put("commentBoyCount","1");
        }
        if (map.get("type").equals("6")){
                map.put("commentGirlCount","1");
        }
        }
        Query query = new Query(map);
        List<TdBook> tdBookList = tdBookService.queryList(query);
        int total = tdBookService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(tdBookList, total, query.getLimit(), query.getPage());
        return R.ok().put("data", pageUtil);
    }

//    /**
//     * 按条件查询所有
//     * <p>
//     * 收藏    coolection
//     * 付费    pay
//     *
//     * @return
//     */
//    @AuthIgnore
//    @PostMapping("findAllByCollPay")
//    public R findAllByCollPay(@RequestParam Map<String, Object> map) {
//        if (map.get("pay") != null) {
//            map.put("orderStatus", PayStatus.success);
//            map.put("grop", "bookid");
//            map.put("payType","out");
//            Query query = new Query(map);
//            List<TdOrder> tdOrderList = tdOrderService.queryList(query);
//            List<TdBook> tdBookList = new ArrayList<>();
//            for (int i = 0; i < tdOrderList.size(); i++) {
//                tdBookList.add(tdBookService.selectByPrimaryKey(tdOrderList.get(i).getBookid()));
//            }
//            PageUtils pageUtil = new PageUtils(tdBookList, tdBookList.size(), query.getLimit(), query.getPage());
//            return R.ok().put("list", pageUtil);
//        } else if (map.get("coolection") != null) {
//            Query query = new Query(map);
//            map.put("grop", "bookid");
//            List<TdCollection> tdCollectionList = tdCollectionService.queryList(query);
//            List<TdBook> tdBookList = new ArrayList<>();
//            for (int i = 0; i < tdCollectionList.size(); i++) {
//                tdBookList.add(tdBookService.selectByPrimaryKey(tdCollectionList.get(i).getBookid()));
//            }
//            PageUtils pageUtil = new PageUtils(tdBookList, tdBookList.size(), query.getLimit(), query.getPage());
//            return R.ok().put("list", pageUtil);
//        }
//        return R.error("未查询到数据");
//
//    }

    /*
    * 猜你喜欢
    */
    @AuthIgnore
    @RequestMapping("/guessLike")
    public R guessLike(){
        List<TdBook> tdBooks = tdBookService.findByRand();
        return R.ok().put("data",tdBooks);
    }

    /*
    * 搜索时随机推荐一本
    */
    @AuthIgnore
    @RequestMapping("/recommendBook")
    public R recommendBook(){
        TdBook tdBook = tdBookService.findOneByRand();
        return R.ok().put("data",tdBook);
    }

    /*
    * 我要推荐（点赞）
    */
    @RequestMapping("/dianzan")
    public R dianzan(@LoginUser TbUser tbUser, Integer id){
        //找到图书
        TdBook tdBook = tdBookService.selectByPrimaryKey(id);
        if (tdBook==null){
            return R.error("查无此书");
        }
        //首先根据bookid和userid去查找图书推荐记录
        TbBookRecommendRecord tbBookRecommendRecord = tbBookRecommendRecordService.findByBookidAndUserid(tbUser.getUserId(),id);
        if (tbBookRecommendRecord==null){
            //增加图书点赞数
            tdBook.setLikeCount(tdBook.getLikeCount()+1);
            //创建记录
            TbBookRecommendRecord tbBookRecommendRecord1 = new TbBookRecommendRecord();
            tbBookRecommendRecord1.setUserid(tbUser.getUserId());
            tbBookRecommendRecord1.setBookid(tdBook.getId());
            tbBookRecommendRecord1.setCreatedate(new Date());
            //保存记录
            tbBookRecommendRecordService.save(tbBookRecommendRecord1);
            //更新图书信息
            tdBookService.updateByPrimaryKey(tdBook);
            return R.ok();
        }else {
            return R.error("请勿重复推荐");
        }
    }

    /*
    * 图书评分
    */
    @RequestMapping("/grade")
    public R grade(@LoginUser TbUser tbUser, Integer id, Double grade){
        //首先更根据用户id查询打分记录，判断用户是否打过分了。
        TbGradeRecord tbGradeRecord = tbGradeRecordService.findByUserIdAndBookId(tbUser.getUserId(),id);
        //找到图书
        TdBook tdBook = tdBookService.selectByPrimaryKey(id);
        if (tdBook==null){
            return R.error("图书不存在啦");
        }
        //如果存在就提醒用户，不存在才能打分
        if (tbGradeRecord==null){
            //先分别加入总评分，和增加评分人数。
            tdBook.setGradeSum(tdBook.getGradeSum()+grade);
            tdBook.setGradeNumber(tdBook.getGradeNumber()+1);
            //计算平均值
            tdBook.setGrade(tdBook.getGradeSum()/tdBook.getGradeNumber());
            //更新图书信息
            tdBookService.updateByPrimaryKey(tdBook);
            //创建打分记录
            TbGradeRecord tbGradeRecord1 = new TbGradeRecord();
            tbGradeRecord1.setUserId(tbUser.getUserId());
            tbGradeRecord1.setGrade(grade);
            tbGradeRecord1.setCreateDate(new Date());
            tbGradeRecord1.setBookId(tdBook.getId());
            //保存记录
            tbGradeRecordService.save(tbGradeRecord1);
            return R.ok();
        }else {
            return R.error("请勿多次评分");
        }

    }


    /*
    * 查询
    */
}
